/*
 * @Author: your name
 * @Date: 2024-04-18 10:54:00
 * @LastEditTime: 2024-04-18 11:00:46
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\637.二叉树的层平均值.cpp
 */
/*
 * @lc app=leetcode.cn id=637 lang=cpp
 *
 * [637] 二叉树的层平均值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        // 存储平均值的数组 
        vector<double> res;
        if(root == nullptr){
            return res;
        }
        // 存储每个树节点
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()){
            int size = que.size();
            double sum = 0.0;
            for(int i = 0; i < size; i++){
                // 获取队列第一个元素并弹出
                TreeNode* tmp_node = que.front();
                que.pop();
                // 计算和
                sum += tmp_node->val;
                // 添加左右节点
                if(tmp_node->left) que.push(tmp_node->left);
                if(tmp_node->right) que.push(tmp_node->right);
            }
            res.push_back(sum/size);
        }
        return res;
    }
};
// @lc code=end

